package mtons.cast.interceptor;

import com.alibaba.fastjson.JSONObject;
import mtons.cast.modules.data.Result;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by langhsu on 2017/10/13.
 */
public class AccessInterceptor extends HandlerInterceptorAdapter {
    static String LOGIN_URL = "/login";

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();

        if (!request.getRequestURI().contains(LOGIN_URL)) {
            Object bean = session.getAttribute("profile");
            if (bean == null) {
                String to = request.getContextPath() + LOGIN_URL;

                if (isAjax(handler)) {
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().print(JSONObject.toJSONString(Result.error("您还没有登录!")));
                } else {
                    response.sendRedirect(LOGIN_URL);
                }
                return false;
            }
        }
        return true;
    }

    private boolean isAjax(Object handler) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        ResponseBody responseBodyAnn = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), ResponseBody.class);
        return responseBodyAnn != null;
    }

}
